package com.teragadgets.android.comic;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.RelativeLayout;

import com.teragadgets.android.comic.datamodel.Comic;

public class ComicActivity extends Activity implements Observer,
		OnTouchListener, OnClickListener {

	private ComicModel model;
	private WebView webView;
	private NavigationControls navControls;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);
		this.setContentView(R.layout.comicview);

		webView = (WebView) findViewById(R.id.webview);
		webView.setOnTouchListener(this);
		final Activity activity = this;
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				activity.setProgress(progress * 100);
			}
		});

		navControls = new NavigationControls(this);
		RelativeLayout navLayout = (RelativeLayout) this
				.findViewById(R.id.nav_holder);
		navLayout.addView(navControls);

		navControls.setOnLeftArrowClickListener(this);
		navControls.setOnRightArrowClickListener(this);

		// Initialize Model
		model = new ComicModel(this, getIntent().getStringExtra("webComicID"),
				getIntent().getIntExtra("comicID", -1));
		model.addObserver(this);
		model.reloadCurrentComic(this);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void update(Observable observable, Object data) {
		if (data != null) {
			Comic comic = (Comic) data;
			this.setTitle(comic.toString());
			webView.loadData(comic.getData(), "text/html", "utf-8");
			navControls.quickShow();
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN)
			navControls.show();
		else if (event.getAction() == MotionEvent.ACTION_UP)
			navControls.hide();
		return false;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.left_arrow_wrapper)
			model.loadNextComic(this);
		else if (v.getId() == R.id.right_arrow_wrapper)
			model.loadPreviousComic(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		model.save(this);
	}
}
